<?php


namespace WenRuns\Laravel\Admin\Grid;


use Encore\Admin\Facades\Admin;
use WenRuns\Laravel\Admin\Grid;

class SubColumn
{
    protected $parentColumn;


    /**
     * SubColumn constructor.
     * @param Column $column
     */
    public function __construct(Column $column)
    {
        $this->parentColumn = $column;
        $column->setAttributes([
            'parent-column' => 'true',
        ]);
    }

    protected function resetStyle(Column $column)
    {
        $column->setAttributes([
            'sub-column' => 'true',
        ]);
        $style = <<<STYLE
.grid-box table th[parent-column="true"]{
    text-align: center;
    border-left: 1px solid #f4f4f4;
    border-right: 1px solid #f4f4f4;
}
.grid-box table th[sub-column="true"]{
    border-left: 1px solid #f4f4f4;
    border-right: 1px solid #f4f4f4;
}
STYLE;
        Admin::style($style);
        return $this;
    }

    /**
     * @return Grid
     */
    public function getGrid()
    {
        return $this->parentColumn->getGrid();
    }

    /**
     * @param $name
     * @param $label
     * @return bool|\Encore\Admin\Grid|\Encore\Admin\Grid\Column|\Illuminate\Support\HigherOrderTapProxy|Grid|Column
     */
    public function column($name, $label)
    {
        $grid = $this->getGrid();
        $column = $grid->column($name, $label);
        $this->resetLevel($column);
        $this->resetStyle($column);
        $this->resetParentColspan();
        $grid->mutators[$this->getParentLevel()][] = $column;
        $grid->mutatorColumns[] = $column->getName();
        return $column;
    }

    protected function getParentLevel()
    {
        return $this->parentColumn->rowLevel;
    }

    protected function resetLevel(Column $column)
    {
        $column->rowLevel = $this->getParentLevel() + 1;
        return $this;
    }

    protected function resetParentColspan()
    {
        $this->parentColumn->colspan++;
        return $this;
    }
}